<template>
  <div class="order-lifecycle-container">
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <h3>采购订单生命周期管理</h3>
          <div class="operation-buttons">
            <el-button type="primary" @click="createOrder">新建订单</el-button>
            <el-button @click="batchExport" :disabled="!(selectedOrders && selectedOrders.length)">批量导出</el-button>
          </div>
        </div>
      </template>
      
      <el-form :model="filterForm" label-width="100px" :inline="true">
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择订单状态" clearable multiple collapse-tags>
            <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="供应商">
          <el-select v-model="filterForm.supplierId" placeholder="请选择供应商" clearable filterable>
            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 订单列表 -->
    <el-card class="order-list-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号"  />
        <el-table-column prop="supplierName" label="供应商名称" />
        <el-table-column prop="totalAmount" label="订单金额(元)">
          <template #default="scope">
            {{ formatPrice(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="expectedDeliveryDate" label="预计交付日期" />
        <el-table-column prop="status" label="订单状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">查看详情</el-button>
            <el-button type="primary" link @click="viewTimeline(scope.row)" v-if="scope.row.status !== 'draft'">查看流程</el-button>
            <el-button type="primary" link @click="handleNextAction(scope.row)">{{ getActionButtonText(scope.row.status) }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="采购订单详情"
      width="80%"
      destroy-on-close
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="order-header">
          <div class="order-title">
            <h2>订单编号：{{ currentOrder.orderNo }}</h2>
            <el-tag :type="getStatusTagType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </div>
          <div class="order-meta">
            <p><span>创建时间：</span>{{ currentOrder.createTime }}</p>
            <p><span>创建人：</span>{{ currentOrder.creatorName }}</p>
            <p><span>预计交付日期：</span>{{ currentOrder.expectedDeliveryDate }}</p>
          </div>
        </div>
        
        <el-divider content-position="left">供应商信息</el-divider>
        <div class="supplier-info">
          <p><span>供应商名称：</span>{{ currentOrder.supplierName }}</p>
          <p><span>联系人：</span>{{ currentOrder.supplierContactName }}</p>
          <p><span>联系电话：</span>{{ currentOrder.supplierContactPhone }}</p>
          <p><span>电子邮箱：</span>{{ currentOrder.supplierEmail }}</p>
          <p><span>地址：</span>{{ currentOrder.supplierAddress }}</p>
        </div>
        
        <el-divider content-position="left">订单明细</el-divider>
        <el-table
          :data="currentOrder.items"
          border
          style="width: 100%"
        >
          <el-table-column prop="materialCode" label="物料编码" width="120" />
          <el-table-column prop="materialName" label="物料名称" width="180" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="unitPrice" label="单价(元)" width="120">
            <template #default="scope">
              {{ formatPrice(scope.row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="总价(元)" width="150">
            <template #default="scope">
              {{ formatPrice(scope.row.unitPrice * scope.row.quantity) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
        
        <div class="order-summary">
          <p><span>订单总金额：</span>{{ formatPrice(currentOrder.totalAmount) }} 元</p>
          <p><span>付款方式：</span>{{ currentOrder.paymentMethod }}</p>
          <p><span>付款条件：</span>{{ currentOrder.paymentTerms }}</p>
        </div>
        
        <el-divider content-position="left">审批记录</el-divider>
        <el-table
          :data="currentOrder.approvalRecords"
          border
          style="width: 100%"
        >
          <el-table-column prop="stageName" label="审批节点" width="150" />
          <el-table-column prop="approverName" label="审批人" width="120" />
          <el-table-column prop="approveTime" label="审批时间" width="180" />
          <el-table-column prop="result" label="审批结果" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.result === 'approved' ? 'success' : 'danger'">
                {{ scope.row.result === 'approved' ? '通过' : '驳回' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="审批意见" />
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDetailAction" v-if="currentOrder && canTakeAction(currentOrder.status)">
            {{ getActionButtonText(currentOrder?.status) }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 订单流程时间线弹窗 -->
    <el-dialog
      v-model="timelineVisible"
      title="订单流程时间线"
      width="60%"
      destroy-on-close
    >
      <div v-if="currentOrder && currentOrder.orderNo" class="timeline-container">
        <h3>订单号：{{ currentOrder.orderNo }}</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentOrder.timeline || []"
            :key="index"
            :type="activity.type"
            :color="activity.color"
            :size="activity.size"
            :timestamp="activity.timestamp"
          >
            {{ activity.content }}
            <p v-if="activity.description" class="timeline-description">{{ activity.description }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
    
    <!-- 订单操作确认框 -->
    <el-dialog
      v-model="actionDialogVisible"
      :title="actionDialogTitle"
      width="50%"
      destroy-on-close
    >
      <div v-if="currentOrder" class="action-form">
        <el-form :model="actionForm" label-width="120px">
          <el-form-item :label="actionFormLabel" v-if="actionType !== 'cancel'">
            <el-input
              v-model="actionForm.comment"
              :placeholder="actionInputPlaceholder"
              type="textarea"
              rows="4"
            />
          </el-form-item>
          
          <el-form-item label="上传附件" v-if="['submit', 'approve', 'deliver'].includes(actionType)">
            <el-upload
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :file-list="actionForm.fileList"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传相关支持文件，支持PDF、Word、Excel等格式</div>
              </template>
            </el-upload>
          </el-form-item>
          
          <el-form-item label="实际交付日期" v-if="actionType === 'deliver'">
            <el-date-picker
              v-model="actionForm.deliveryDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          
          <el-form-item label="取消原因" v-if="actionType === 'cancel'">
            <div class="full-width-select">
              <el-select v-model="actionForm.cancelReason" placeholder="请选择取消原因">
                <el-option label="供应商无法按时交付" value="supplier_delay" />
                <el-option label="价格变动" value="price_change" />
                <el-option label="需求变更" value="requirement_change" />
                <el-option label="质量问题" value="quality_issue" />
                <el-option label="其他原因" value="other" />
              </el-select>
            </div>
            <el-input
              v-if="actionForm.cancelReason === 'other'"
              v-model="actionForm.comment"
              placeholder="请输入取消原因"
              type="textarea"
              rows="3"
              style="margin-top: 10px"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="actionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAction">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 新建订单弹窗 -->
    <el-dialog
      v-model="createOrderDialogVisible"
      title="新建采购订单"
      width="80%"
      destroy-on-close
    >
      <el-form :model="newOrderForm" :rules="newOrderRules" ref="newOrderFormRef" label-width="120px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="newOrderForm.orderNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计交付日期" prop="expectedDeliveryDate">
              <el-date-picker
                v-model="newOrderForm.expectedDeliveryDate"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单类型" prop="orderType" class="full-width-select">
              <el-select v-model="newOrderForm.orderType" placeholder="请选择订单类型">
                <el-option label="常规采购" value="regular" />
                <el-option label="紧急采购" value="urgent" />
                <el-option label="战略采购" value="strategic" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">供应商信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId" class="full-width-select">
              <el-select 
                v-model="newOrderForm.supplierId" 
                placeholder="请选择供应商" 
                filterable 
                @change="handleSupplierChange"
              >
                <el-option 
                  v-for="item in supplierOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="supplierContactName">
              <el-input v-model="newOrderForm.supplierContactName" placeholder="供应商联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="supplierContactPhone">
              <el-input v-model="newOrderForm.supplierContactPhone" placeholder="联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="电子邮箱" prop="supplierEmail">
              <el-input v-model="newOrderForm.supplierEmail" placeholder="电子邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="供应商地址" prop="supplierAddress">
              <el-input v-model="newOrderForm.supplierAddress" placeholder="供应商地址" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">订单明细</el-divider>
        <div class="order-items-header">
          <div></div>
          <el-button type="primary" link @click="addOrderItem">
            <el-icon><Plus /></el-icon> 添加物料
          </el-button>
        </div>
        <el-table :data="newOrderForm.items" border style="width: 100%">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="物料" width="200">
            <template #default="scope">
              <div class="full-width-select">
                <el-select 
                  v-model="scope.row.materialId" 
                  filterable 
                  placeholder="选择物料"
                  @change="(val) => handleMaterialChange(val, scope.$index)"
                >
                  <el-option 
                    v-for="item in materialOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialCode" label="物料编码" width="120" />
          <el-table-column prop="materialName" label="物料名称" width="150" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column label="数量" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                @change="calculateItemTotal(scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.unitPrice"
                :precision="2"
                :step="0.01"
                :min="0"
                @change="calculateItemTotal(scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="总价(元)" width="120">
            <template #default="scope">
              {{ formatPrice(scope.row.totalPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="danger" link @click="removeOrderItem(scope.$index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="order-summary-info">
          <p>订单总金额：<span>{{ formatPrice(orderTotalAmount) }} 元</span></p>
        </div>
        
        <el-divider content-position="left">付款信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="付款方式" prop="paymentMethod" class="full-width-select">
              <el-select v-model="newOrderForm.paymentMethod" placeholder="请选择付款方式">
                <el-option label="银行转账" value="bank_transfer" />
                <el-option label="支票" value="check" />
                <el-option label="现金" value="cash" />
                <el-option label="电子支付" value="electronic" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="付款条件" prop="paymentTerms" class="full-width-select">
              <el-select v-model="newOrderForm.paymentTerms" placeholder="请选择付款条件">
                <el-option label="预付款30%，验收合格后7天内付款70%" value="30_advance_70_after" />
                <el-option label="货到付款，验收合格后30天内付款" value="payment_after_30days" />
                <el-option label="分期付款（首付30%，交付后30%，验收合格后40%）" value="installment_30_30_40" />
                <el-option label="月结60天" value="monthly_60days" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">其他说明</el-divider>
        <el-form-item label="订单备注">
          <el-input
            v-model="newOrderForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入订单相关说明或备注"
          />
        </el-form-item>
        
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="newOrderForm.fileList"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传相关支持文件，支持PDF、Word、Excel等格式</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAsDraft">保存为草稿</el-button>
          <el-button type="success" @click="submitNewOrder">提交审批</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
// import { fetchOrderList, getOrderDetail, submitOrder, approveOrder, rejectOrder, deliverOrder, receiveOrder, cancelOrder } from '@/api/order'

export default {
  name: 'OrderLifecycle',
  components: {
    Plus,
    Delete
  },
  setup() {
    // 状态和数据
    const loading = ref(false)
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const selectedOrders = ref([])
    const orderDetailVisible = ref(false)
    const timelineVisible = ref(false)
    const actionDialogVisible = ref(false)
    const createOrderDialogVisible = ref(false)
    const currentOrder = ref(null)
    const actionType = ref('')
    const newOrderFormRef = ref(null)
    
    // 操作表单
    const actionForm = reactive({
      comment: '',
      fileList: [],
      deliveryDate: '',
      cancelReason: ''
    })
    
    // 添加filterForm的初始化
    const filterForm = reactive({
      orderNo: '',
      status: [],
      supplierId: '',
      dateRange: []
    })
    
    // 订单状态选项
    const orderStatusOptions = [
      { value: 'draft', label: '草稿' },
      { value: 'pending_approval', label: '待审批' },
      { value: 'approved', label: '已审批' },
      { value: 'rejected', label: '已驳回' },
      { value: 'in_progress', label: '执行中' },
      { value: 'delivered', label: '已交付' },
      { value: 'completed', label: '已完成' },
      { value: 'cancelled', label: '已取消' }
    ]
    
    // 供应商选项
    const supplierOptions = [
      { value: 'S001', label: '上海钢铁有限公司', contactName: '张经理', contactPhone: '13800138001', email: 'contact@shisteel.com', address: '上海市宝山区钢铁大道123号' },
      { value: 'S002', label: '江苏精密机械制造有限公司', contactName: '李工', contactPhone: '13900139002', email: 'contact@jsprecision.com', address: '江苏省苏州市工业园区机械路456号' },
      { value: 'S003', label: '广东电子科技有限公司', contactName: '王总', contactPhone: '13700137003', email: 'contact@gdelectronics.com', address: '广东省深圳市南山区科技园789号' }
    ]
    
    // 新增物料选项数据
    const materialOptions = [
      { value: 'M001', label: '钢板', code: 'M001', name: '钢板', specification: '1000x2000x1.5mm', unit: '张', price: 120 },
      { value: 'M002', label: '螺丝', code: 'M002', name: '螺丝', specification: 'M8x30', unit: '盒', price: 25 },
      { value: 'M003', label: '轴承', code: 'M003', name: '轴承', specification: '608ZZ', unit: '个', price: 18.5 },
      { value: 'M004', label: '铝型材', code: 'M004', name: '铝型材', specification: '40x40mm', unit: '米', price: 35 },
      { value: 'M005', label: '电线', code: 'M005', name: '电线', specification: '2.5mm²', unit: '卷', price: 280 }
    ]
    
    // 新建订单表单
    const newOrderForm = reactive({
      orderNo: 'PO-' + new Date().getFullYear() + (new Date().getMonth() + 1).toString().padStart(2, '0') + new Date().getDate().toString().padStart(2, '0') + '-' + Math.floor(Math.random() * 1000).toString().padStart(3, '0'),
      expectedDeliveryDate: '',
      orderType: 'regular',
      supplierId: '',
      supplierName: '',
      supplierContactName: '',
      supplierContactPhone: '',
      supplierEmail: '',
      supplierAddress: '',
      paymentMethod: 'bank_transfer',
      paymentTerms: 'payment_after_30days',
      remark: '',
      fileList: [],
      items: []
    })
    
    // 表单验证规则
    const newOrderRules = {
      expectedDeliveryDate: [
        { required: true, message: '请选择预计交付日期', trigger: 'blur' }
      ],
      supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
      ],
      supplierContactName: [
        { required: true, message: '请输入供应商联系人', trigger: 'blur' }
      ],
      supplierContactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ]
    }
    
    // 订单总金额计算
    const orderTotalAmount = computed(() => {
      return newOrderForm.items.reduce((total, item) => {
        return total + (item.totalPrice || 0)
      }, 0)
    })
    
    // 操作对话框标题
    const actionDialogTitle = computed(() => {
      const titleMap = {
        'submit': '提交订单审批',
        'approve': '审批订单',
        'reject': '驳回订单',
        'deliver': '确认交付',
        'receive': '确认收货',
        'complete': '完成订单',
        'cancel': '取消订单',
        'edit': '修改订单'
      }
      return titleMap[actionType.value] || '订单操作'
    })
    
    // 操作表单标签
    const actionFormLabel = computed(() => {
      const labelMap = {
        'submit': '提交说明',
        'approve': '审批意见',
        'reject': '驳回理由',
        'deliver': '交付说明',
        'receive': '收货备注',
        'complete': '完成备注',
        'edit': '修改说明'
      }
      return labelMap[actionType.value] || '备注'
    })
    
    // 操作输入框占位符
    const actionInputPlaceholder = computed(() => {
      const placeholderMap = {
        'submit': '请输入提交说明',
        'approve': '请输入审批意见',
        'reject': '请输入驳回理由',
        'deliver': '请输入交付说明',
        'receive': '请输入收货备注',
        'complete': '请输入完成备注',
        'edit': '请输入修改说明'
      }
      return placeholderMap[actionType.value] || '请输入备注'
    })
    
    // 方法
    // ... existing methods ...
    
    // 新建订单弹窗
    const createOrder = () => {
      // 重置表单
      Object.assign(newOrderForm, {
        orderNo: 'PO-' + new Date().getFullYear() + (new Date().getMonth() + 1).toString().padStart(2, '0') + new Date().getDate().toString().padStart(2, '0') + '-' + Math.floor(Math.random() * 1000).toString().padStart(3, '0'),
        expectedDeliveryDate: '',
        orderType: 'regular',
        supplierId: '',
        supplierName: '',
        supplierContactName: '',
        supplierContactPhone: '',
        supplierEmail: '',
        supplierAddress: '',
        paymentMethod: 'bank_transfer',
        paymentTerms: 'payment_after_30days',
        remark: '',
        fileList: [],
        items: []
      })
      createOrderDialogVisible.value = true
    }
    
    // 处理供应商选择变更
    const handleSupplierChange = (value) => {
      const selectedSupplier = supplierOptions.find(item => item.value === value)
      if (selectedSupplier) {
        newOrderForm.supplierName = selectedSupplier.label
        newOrderForm.supplierContactName = selectedSupplier.contactName
        newOrderForm.supplierContactPhone = selectedSupplier.contactPhone
        newOrderForm.supplierEmail = selectedSupplier.email
        newOrderForm.supplierAddress = selectedSupplier.address
      }
    }
    
    // 处理物料选择变更
    const handleMaterialChange = (value, index) => {
      const selectedMaterial = materialOptions.find(item => item.value === value)
      if (selectedMaterial && newOrderForm.items[index]) {
        newOrderForm.items[index].materialCode = selectedMaterial.code
        newOrderForm.items[index].materialName = selectedMaterial.name
        newOrderForm.items[index].specification = selectedMaterial.specification
        newOrderForm.items[index].unit = selectedMaterial.unit
        newOrderForm.items[index].unitPrice = selectedMaterial.price
        calculateItemTotal(index)
      }
    }
    
    // 计算单项总价
    const calculateItemTotal = (index) => {
      const item = newOrderForm.items[index]
      if (item && item.quantity && item.unitPrice) {
        item.totalPrice = item.quantity * item.unitPrice
      }
    }
    
    // 添加订单项
    const addOrderItem = () => {
      newOrderForm.items.push({
        materialId: '',
        materialCode: '',
        materialName: '',
        specification: '',
        unit: '',
        quantity: 1,
        unitPrice: 0,
        totalPrice: 0,
        remark: ''
      })
    }
    
    // 移除订单项
    const removeOrderItem = (index) => {
      newOrderForm.items.splice(index, 1)
    }
    
    // 保存为草稿
    const saveAsDraft = () => {
      if (newOrderForm.items.length === 0) {
        ElMessage.warning('请添加至少一项物料')
        return
      }
      
      // 实际项目中这里应该调用API保存草稿
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('订单已保存为草稿')
        createOrderDialogVisible.value = false
        loadData() // 重新加载数据
      }, 800)
    }
    
    // 提交新订单
    const submitNewOrder = () => {
      if (!newOrderFormRef.value) return
      
      newOrderFormRef.value.validate(valid => {
        if (!valid) {
          ElMessage.error('请完善必填信息')
          return
        }
        
        if (newOrderForm.items.length === 0) {
          ElMessage.warning('请添加至少一项物料')
          return
        }
        
        // 检查物料明细是否完整
        const invalidItems = newOrderForm.items.filter(item => !item.materialId || !item.quantity || item.unitPrice <= 0)
        if (invalidItems.length > 0) {
          ElMessage.warning('请完善物料明细信息')
          return
        }
        
        // 实际项目中这里应该调用API提交订单
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('订单已提交审批')
          createOrderDialogVisible.value = false
          loadData() // 重新加载数据
        }, 800)
      })
    }
    
    // 查看订单流程时间线
    const viewTimeline = (order) => {
      if (!order || !order.orderNo) {
        ElMessage.error('订单数据不完整')
        return
      }
      currentOrder.value = order
      timelineVisible.value = true
    }
    
    // 处理下一步操作
    const handleNextAction = (order) => {
      if (!order || !order.orderNo) {
        ElMessage.error('订单数据不完整')
        return
      }
      currentOrder.value = order
      actionType.value = getNextAction(order.status)
      if (!actionType.value) return
      
      actionDialogVisible.value = true
    }
    
    // 获取下一步操作类型
    const getNextAction = (status) => {
      const actionMap = {
        'draft': 'submit',
        'pending_approval': 'approve',
        'approved': 'deliver',
        'in_progress': 'receive',
        'delivered': 'complete',
        'completed': null,
        'rejected': 'edit',
        'cancelled': null
      }
      return actionMap[status] || null
    }
    
    // 格式化价格
    const formatPrice = (price) => {
      if (!price && price !== 0) return '0.00'
      return Number(price).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
    
    // 获取订单状态标签类型
    const getStatusTagType = (status) => {
      const typeMap = {
        'draft': 'info',
        'pending_approval': 'warning',
        'approved': 'success',
        'rejected': 'danger',
        'in_progress': 'primary',
        'delivered': 'success',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    // 获取订单状态文本
    const getStatusText = (status) => {
      const textMap = {
        'draft': '草稿',
        'pending_approval': '待审批',
        'approved': '已审批',
        'rejected': '已驳回',
        'in_progress': '执行中',
        'delivered': '已交付',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return textMap[status] || '未知状态'
    }
    
    // 获取操作按钮文本
    const getActionButtonText = (status) => {
      const textMap = {
        'draft': '提交审批',
        'pending_approval': '审批',
        'approved': '确认交付',
        'in_progress': '确认收货',
        'delivered': '完成订单',
        'rejected': '修改重提',
        'completed': '',
        'cancelled': ''
      }
      return textMap[status] || ''
    }
    
    // 判断是否可以执行操作
    const canTakeAction = (status) => {
      return ['draft', 'pending_approval', 'approved', 'in_progress', 'delivered', 'rejected'].includes(status)
    }
    
    // 处理选择变更
    const handleSelectionChange = (selection) => {
      selectedOrders.value = selection
    }
    
    // 批量导出
    const batchExport = () => {
      if (!selectedOrders.value || selectedOrders.value.length === 0) {
        ElMessage.warning('请选择要导出的订单')
        return
      }
      // 实际项目中这里应该调用API导出订单
      ElMessage.success(`已导出 ${selectedOrders.value.length} 个订单`)
    }
    
    // 查看订单详情
    const viewDetail = (order) => {
      if (!order || !order.orderNo) {
        ElMessage.error('订单数据不完整')
        return
      }
      currentOrder.value = order
      orderDetailVisible.value = true
    }
    
    // 从详情弹窗执行操作
    const handleDetailAction = () => {
      if (!currentOrder.value) return
      handleNextAction(currentOrder.value)
    }
    
    // 加载数据
    const loadData = () => {
      loading.value = true
      // 实际项目中这里应该调用API获取订单数据
      // 模拟API调用
      setTimeout(() => {
        // 模拟数据
        tableData.value = [
          {
            orderNo: 'PO-20230501-001',
            supplierName: '上海钢铁有限公司',
            totalAmount: 12500.00,
            createTime: '2023-05-01 10:23:45',
            expectedDeliveryDate: '2023-05-15',
            status: 'completed',
            supplierId: 'S001',
            supplierContactName: '张经理',
            supplierContactPhone: '13800138001',
            supplierEmail: 'contact@shisteel.com',
            supplierAddress: '上海市宝山区钢铁大道123号',
            creatorName: '李采购',
            items: [
              { materialCode: 'M001', materialName: '钢板', specification: '1000x2000x1.5mm', unit: '张', quantity: 100, unitPrice: 120 },
              { materialCode: 'M002', materialName: '螺丝', specification: 'M8x30', unit: '盒', quantity: 20, unitPrice: 25 }
            ],
            approvalRecords: [
              { stageName: '部门经理审批', approverName: '张经理', approveTime: '2023-05-02 09:15:30', result: 'approved', comment: '同意采购' }
            ],
            timeline: [
              { content: '创建订单', description: '李采购创建了采购订单', timestamp: '2023-05-01 10:23:45', type: 'primary', color: '#409EFF', size: 'large' },
              { content: '提交审批', description: '订单已提交审批流程', timestamp: '2023-05-01 14:05:22', type: 'primary', color: '#E6A23C', size: 'normal' },
              { content: '审批通过', description: '张经理批准了订单', timestamp: '2023-05-02 09:15:30', type: 'success', color: '#67C23A', size: 'normal' },
              { content: '确认交付', description: '供应商已确认交付日期', timestamp: '2023-05-10 11:30:15', type: 'primary', color: '#409EFF', size: 'normal' },
              { content: '完成交付', description: '物料已全部交付入库', timestamp: '2023-05-14 16:45:12', type: 'success', color: '#67C23A', size: 'large' }
            ],
            paymentMethod: '银行转账',
            paymentTerms: '货到付款，验收合格后30天内付款'
          },
          {
            orderNo: 'PO-20230510-002',
            supplierName: '江苏精密机械制造有限公司',
            totalAmount: 35800.00,
            createTime: '2023-05-10 14:35:20',
            expectedDeliveryDate: '2023-05-30',
            status: 'in_progress',
            supplierId: 'S002',
            supplierContactName: '李工',
            supplierContactPhone: '13900139002',
            supplierEmail: 'contact@jsprecision.com',
            supplierAddress: '江苏省苏州市工业园区机械路456号',
            creatorName: '王采购',
            items: [
              { materialCode: 'M003', materialName: '轴承', specification: '608ZZ', unit: '个', quantity: 500, unitPrice: 18.5 },
              { materialCode: 'M004', materialName: '铝型材', specification: '40x40mm', unit: '米', quantity: 600, unitPrice: 35 }
            ],
            approvalRecords: [
              { stageName: '部门经理审批', approverName: '张经理', approveTime: '2023-05-11 10:25:30', result: 'approved', comment: '同意采购' },
              { stageName: '财务审批', approverName: '赵财务', approveTime: '2023-05-11 15:40:12', result: 'approved', comment: '财务已审核，资金已准备' }
            ],
            timeline: [
              { content: '创建订单', description: '王采购创建了采购订单', timestamp: '2023-05-10 14:35:20', type: 'primary', color: '#409EFF', size: 'large' },
              { content: '提交审批', description: '订单已提交审批流程', timestamp: '2023-05-10 16:20:33', type: 'primary', color: '#E6A23C', size: 'normal' },
              { content: '部门审批', description: '张经理批准了订单', timestamp: '2023-05-11 10:25:30', type: 'success', color: '#67C23A', size: 'normal' },
              { content: '财务审批', description: '赵财务批准了订单', timestamp: '2023-05-11 15:40:12', type: 'success', color: '#67C23A', size: 'normal' }
            ],
            paymentMethod: '电子支付',
            paymentTerms: '预付款30%，验收合格后7天内付款70%'
          }
        ]
        total.value = 2
        loading.value = false
      }, 800)
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置表单
    const resetForm = () => {
      filterForm.orderNo = ''
      filterForm.status = []
      filterForm.supplierId = ''
      filterForm.dateRange = []
      handleSearch()
    }
    
    // 确认操作
    const confirmAction = () => {
      // 实际项目中这里应该调用API执行相应操作
      ElMessage.success('操作成功')
      actionDialogVisible.value = false
      loadData() // 重新加载数据
    }
    
    // 处理文件变更
    const handleFileChange = (file, fileList) => {
      // 文件上传处理
      console.log('File changed:', file)
    }
    
    // 初始化
    onMounted(() => {
      loadData()
    })
    
    return {
      // 状态
      loading,
      tableData,
      currentPage,
      pageSize,
      total,
      selectedOrders,
      orderDetailVisible,
      timelineVisible,
      actionDialogVisible,
      createOrderDialogVisible,
      currentOrder,
      actionType,
      filterForm,
      orderStatusOptions,
      supplierOptions,
      
      // 新订单表单相关
      newOrderForm,
      newOrderRules,
      newOrderFormRef,
      materialOptions,
      orderTotalAmount,
      
      // 操作表单相关
      actionForm,
      actionDialogTitle,
      actionFormLabel,
      actionInputPlaceholder,
      
      // 方法
      formatPrice,
      getStatusTagType,
      getStatusText,
      getActionButtonText,
      canTakeAction,
      handleSelectionChange,
      batchExport,
      viewDetail,
      handleDetailAction,
      loadData,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      resetForm,
      confirmAction,
      handleFileChange,
      createOrder,
      handleSupplierChange,
      handleMaterialChange,
      calculateItemTotal,
      addOrderItem,
      removeOrderItem,
      saveAsDraft,
      submitNewOrder,
      viewTimeline,
      handleNextAction,
      getNextAction
    }
  }
}
</script>

<style>
/* 现有的样式 */
.order-lifecycle-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.order-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-header {
  margin-bottom: 20px;
}

.order-title {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.order-meta {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.supplier-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.timeline-container {
  padding: 10px;
}

.timeline-description {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.lowest-price {
  color: #409EFF;
  font-weight: bold;
}

.action-form {
  padding: 10px;
}

.order-meta p span, .supplier-info p span, .order-summary p span {
  font-weight: bold;
  margin-right: 5px;
}

.order-items-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.order-summary-info {
  display: flex;
  justify-content: flex-end;
  margin: 15px 0;
}

.order-summary-info p span {
  font-weight: bold;
  font-size: 16px;
  color: #f56c6c;
  margin-left: 5px;
}

/* 设置所有下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}

.el-form-item.required-label .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>